<template>
  <el-dialog v-model="visible" title="用户信息" :before-close="close">
    <el-form :model="newFrom" :rules="rules">
      <el-form-item label="账号" :label-width="formLabelWidth" prop="username">
        <el-input v-model="newFrom.username" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="姓名" :label-width="formLabelWidth">
        <el-input v-model="newFrom.nickName" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="邮箱" :label-width="formLabelWidth">
        <el-input v-model="newFrom.email" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
        <el-input v-model="newFrom.password" autocomplete="off" type="password"/>
      </el-form-item>
      <el-form-item label="备注" :label-width="formLabelWidth">
        <el-input v-model="newFrom.note" autocomplete="off" type="textarea"/>
      </el-form-item>
      <el-form-item label="是否启用" :label-width="formLabelWidth" v-if="!isAdd">
        <el-radio :label="1" size="large" v-model="newFrom.status">是</el-radio>
        <el-radio :label="0" size="large" v-model="newFrom.status">否</el-radio>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close()">取消</el-button>
        <el-button type="primary" @click="modifyAdmin"
        >确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {reactive, toRefs, ref, watch} from 'vue'
import {updateAdminInfoApi, registerAdminApi} from '../../../../request/api/user'

const props = defineProps<{
  visible: boolean,
  form: AdminObjItf,
  isAdd: boolean
}>()

const validatePwd = (rule: unknown, value: string | undefined, cb: (mse?: string) => void) => {
  if (!value) {
    cb('密码不能为空')
  } else {
    cb()
  }
}

const state = reactive<{
  formLabelWidth: string,
  newFrom: AdminObjItf,
  rules: {}
}>({
  formLabelWidth: '120px',
  newFrom: {},
  rules: {
    username: [{required: true, message: '用户名不能为空', trigger: 'blur'}],
    password: [{validator: validatePwd, trigger: 'blur'}],
  }
})


const {newFrom, formLabelWidth, rules} = toRefs(state)

// 拷贝form
watch(() => props.form, () => {
  newFrom.value = {...props.form}
})

const emit = defineEmits<{
  (event: 'close', r?: 'reload'): void
}>()

// 点击关闭
const close = (data?: 'reload') => {

  // 传到父组件
  emit('close', data)
}

// 确定按钮
const modifyAdmin = () => {
  let result: boolean = false;
  if (props.isAdd) {
    result = add()
  } else {
    result = edit()
  }
  if (result) {
    close('reload')
  }
}
// 新增用户
const add = (): boolean => {
  registerAdminApi(newFrom.value).then(res => {
    return res.code === 200
  })
  return false
}
// 编辑用户
const edit = (): boolean => {
  if (newFrom.value.id) {
    updateAdminInfoApi(newFrom.value.id, newFrom.value).then(res => {
      return res.code === 200
    })
  }
  return false
}

</script>

<style lang="less" scoped>

</style>
